package com.majun.base.operate;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;

public class ErrorHandlingExample {
	public static void main(String[] args) {
		// 示例 1: 使用 Mono 错误处理操作符
		Mono<Object> mono1 = Mono.error(new RuntimeException("Error")).onErrorResume(e -> Mono.just("Recovered"));
		mono1.subscribe(System.out::println); // 输出: Recovered

		Mono<Object> mono2 = Mono.error(new RuntimeException("Error")).onErrorReturn("Default");
		mono2.subscribe(System.out::println); // 输出: Default

		Mono<Object> mono3 = Mono.error(new RuntimeException("Error"))
				.onErrorMap(e -> new IllegalArgumentException("Mapped Error", e));
		mono3.subscribe(System.out::println, Throwable::printStackTrace); // 输出: Mapped Error

		Mono<Object> mono4 = Mono.error(new RuntimeException("Error")).retry(3);
		mono4.subscribe(System.out::println, Throwable::printStackTrace);

		Mono<Object> mono5 = Mono.error(new RuntimeException("Error"))
				.retryWhen(Retry.from(companion -> companion.take(3)));
		mono5.subscribe(System.out::println, Throwable::printStackTrace);

		Mono<Object> mono6 = Mono.error(new RuntimeException("Error"))
				.doOnError(e -> System.out.println("Error occurred: " + e.getMessage()));
		mono6.subscribe(System.out::println, Throwable::printStackTrace);

		// 示例 2: 使用 Flux 错误处理操作符
		Flux<String> flux1 = Flux.just("A", "B").concatWith(Mono.error(new RuntimeException("Error")))
				.onErrorResume(e -> Flux.just("Recovered"));
		flux1.subscribe(System.out::println); // 输出: A B Recovered

		Flux<String> flux2 = Flux.just("A", "B").concatWith(Mono.error(new RuntimeException("Error")))
				.onErrorReturn("Default");
		flux2.subscribe(System.out::println); // 输出: A B Default

		Flux<String> flux3 = Flux.just("A", "B").concatWith(Mono.error(new RuntimeException("Error")))
				.onErrorMap(e -> new IllegalArgumentException("Mapped Error", e));
		flux3.subscribe(System.out::println, Throwable::printStackTrace); // 输出: Mapped Error

		Flux<String> flux4 = Flux.just("A", "B").concatWith(Mono.error(new RuntimeException("Error"))).retry(3);
		flux4.subscribe(System.out::println, Throwable::printStackTrace);

		Flux<String> flux5 = Flux.just("A", "B").concatWith(Mono.error(new RuntimeException("Error")))
				.retryWhen(Retry.from(companion -> companion.take(3)));
		flux5.subscribe(System.out::println, Throwable::printStackTrace);

		Flux<String> flux6 = Flux.just("A", "B").concatWith(Mono.error(new RuntimeException("Error")))
				.doOnError(e -> System.out.println("Error occurred: " + e.getMessage()));
		flux6.subscribe(System.out::println, Throwable::printStackTrace);
	}
}